package com.caldremch.androidfoundation.http;


import com.caldremch.androidfoundation.BuildConfig;
import com.caldremch.androidfoundation.http.convert.MyGsonConverterFactory;

import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author Caldremch
 * @date 2018-09-03 15:38
 * @describe 请求工具类
 **/
public final class RetrofitHelper {

    private static volatile RetrofitHelper sHelper = null;
    private static ApiService sApiService = null;


    private RetrofitHelper() {
        Retrofit retrofit = getRetrofit(getOkHttpBuilder());
        sApiService = retrofit.create(ApiService.class);
    }


    /**
     * 获取retrofit
     * @return
     */
    public static Retrofit getRetrofit(OkHttpClient.Builder builder) {
        return new Retrofit.Builder()
                .baseUrl(ServerConstant.RELEASE_URl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(builder.build())
                .build();
    }


    public static ApiService getsApiService() {
        getInstance();
        return sApiService;
    }

    private static RetrofitHelper getInstance() {

        if (null == sHelper) {

            synchronized (RetrofitHelper.class) {

                if (sHelper == null) {

                    sHelper = new RetrofitHelper();
                }
            }
        }
        return sHelper;
    }

    public static OkHttpClient.Builder getOkHttpBuilder() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        if (BuildConfig.DEBUG) {
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        } else {
            interceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
        }
        builder.addInterceptor(interceptor)
                .retryOnConnectionFailure(true);
        return builder;
    }




}
